from django.shortcuts import render

# Create your views here.
from rest_framework import status
from rest_framework.generics import ListAPIView, CreateAPIView, UpdateAPIView, DestroyAPIView
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework_extensions.cache.mixins import CacheResponseMixin

from areas.models import Area, Address
from areas.serializers import AreasSerializer, AddressSerializers


class ProvinceView(CacheResponseMixin, ListAPIView):
    """返回省份数据"""
    queryset = Area.objects.filter(parent_id=None) # 过滤查询,返回父级为空的数据
    serializer_class = AreasSerializer


class AreasView(CacheResponseMixin, ListAPIView):
    """返回市、区镇数据"""
    serializer_class = AreasSerializer

    def get_queryset(self):
        """
        因为需要使用参数,所以构造一个方法
        :return:
        """
        id = self.kwargs["id"]
        return Area.objects.filter(parent_id=id)


class AddressesView(CreateAPIView, ListAPIView, DestroyAPIView, UpdateAPIView):
    """用户地址管理"""

    """序列化器实现保存和修改收货地址"""
    serializer_class = AddressSerializers
    permissions = [IsAuthenticated]

    def get_queryset(self):
        """
        重写方法,制定查询集
        :return:
        """
        return Address.objects.filter(user = self.request.user,
                                      is_deleted=False)

    def list(self,request, *args, **kwargs):
        """
        返回所有地址
        根据前端需求,重写list方法
        :param request:
        :param args:
        :param kwargs:
        :return:
        """
        queryset = self.filter_queryset(self.get_queryset())
        serializer = self.get_serializer(queryset, many=True)
        return Response({"addresses":serializer.data})

    def destroy(self, request, *args, **kwargs):
        """
        重写删除方法,实现逻辑删除
        :param request:
        :param args:
        :param kwargs:
        :return:
        """
        instance = self.get_object()
        instance.is_deleted = True
        instance.save()
        return Response(status=status.HTTP_204_NO_CONTENT)


class AddressesChangeTitleView(APIView):
    """修改收货地址的标题"""
    def put(self,request,pk):
        """
        修改收货地址标题
        :param requset:
        :param pk:
        :return:
        """

        address = Address.objects.filter(id=pk)[0]
        new_title = request.data["title"]
        address.title = new_title
        address.save()

        return Response("ok")







